package com.zlyx.easy.http.rest;

import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
public class RestComponent {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected RestTemplate restTemplate;

	/**
	 * 发送请求
	 * 
	 * @param <T>
	 * @param url
	 * @param params
	 * @param cls
	 * @return
	 */
	public <T> T requestPost(String url, Map<Object, Object> params, Class<T> cls) {
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
		String key = null;
		String value = null;
		for (Entry<Object, Object> entry : params.entrySet()) {
			if (entry.getValue() != null) {
				key = "" + entry.getKey();
				value = "" + entry.getValue();
				if (url.contains(":" + key)) {
					url = url.replaceAll(":" + key, "" + value);
				} else if (url.contains("{" + key + "}")) {
					url = url.replaceAll("{" + key + "}", "" + value);
				} else {
					requestEntity.add(key, value);
				}
			}
		}
		logger.info("请求地址 ：{}", url);
		logger.info("请求参数 ：{}", requestEntity.toSingleValueMap());
		T response = restTemplate.postForObject(url, requestEntity, cls);
		logger.info("请求结果：{}", response);
		return response;
	}

	/**
	 * 发送 GET请求
	 * 
	 * @param <T>
	 * @param url
	 * @param params
	 * @param cls
	 * @return
	 */
	public <T> T requestGet(String url, Map<?, ?> params, Class<T> cls) {
		StringBuilder sb = new StringBuilder();
		String key = null;
		String value = null;
		for (Entry<?, ?> entry : params.entrySet()) {
			if (entry.getValue() != null) {
				key = "" + entry.getKey();
				value = "" + entry.getValue();
				if (url.contains(":" + key)) {
					url = url.replaceAll(":" + key, "" + value);
				} else if (url.contains("{" + key + "}")) {
					url = url.replaceAll("{" + key + "}", "" + value);
				} else {
					sb.append("&" + key + "=" + value);
				}
			}
		}
		String paramString = sb.toString().replaceFirst("&", "?");
		if (!"?".equals(paramString)) {
			url += paramString;
		}
		logger.info("请求地址 ：{}", url);
		T response = restTemplate.getForObject(url, cls);
		logger.info("请求结果：{}", response);
		return response;
	}
}